///server.c by cme
#include <stdio.h>
#include "tcp_sock.h"
int main(int argc, char* argv[])
{
	unsigned short server_port = 2008;
	int nSock = 0;
	int nRead = 0;
	init_network();
	nSock = tcp_listen_port(server_port);
	if(nSock <= 0)
	{
		printf("tcp listen on prot %d error\n", server_port);
		return 0;
	}
	while(1)
	{
		struct sockaddr_in addr;
		char szFile[128] = {0};
		char szBuff[8192] = {0};
		int fd = -1;
		int nRead = 0;
		int len = sizeof(struct sockaddr);
		int new_sock = accept(nSock, (struct sockaddr*)&(addr), &len);
		if(new_sock <= 0)
		{
#ifdef _WIN32
		Sleep(1000);
#else
			sleep(1);
#endif
			continue;
		}
		printf("one client connected\n");
		if((nRead = recv(new_sock, szFile, 128, 0)) <= 0)
		{
			tcp_close(new_sock);
			continue;
		}
		memset(szFile + nRead, '\0', 128 - nRead);
		strcat(szFile, ".recv");
		#ifdef _WIN32
		if((fd = _open(szFile, O_WRONLY|O_CREAT|O_TRUNC | O_BINARY, 0644)) <= 0)
		#else
		if((fd = open(szFile, O_WRONLY|O_CREAT|O_TRUNC, 0644)) <= 0)
	#endif
		{
			printf("open file %s fail\n", szFile);
			tcp_close(new_sock);
			continue;
		}
		while((nRead = recv(new_sock, szBuff, 8192, 0)) > 0)
		{
			#ifdef _WIN32
			_write(fd, szBuff, nRead);
			#else
			write(fd, szBuff, nRead);
			#endif
			memset(szBuff, 0, 8192);
		}
		#ifdef _WIN32
		_close(fd);
		#else
		close(fd);
		#endif
		printf("file %s transmit over......\n", szFile);
		tcp_close(new_sock);
	}
	return 0;
}
